﻿using System;
using System.Configuration;
using System.Drawing;
namespace CRMSystemV2.Service
{
    public partial class ValidateCode : System.Web.UI.Page
    {
       //验证码长度
        private static readonly int _CodeLength = int.Parse(ConfigurationManager.AppSettings["checkCodeLength"]);
        private Random _Rand = new Random();
        private int _BrushIndex;
        //字体
        private string[] _Fonts = { "Arial", "Helvetica", "Geneva", "sans-serif", "Verdana" };
        //笔刷
        private Brush[] _Brushs = { Brushes.OliveDrab, Brushes.ForestGreen, Brushes.DarkCyan, Brushes.LightSlateGray, Brushes.RoyalBlue, Brushes.SlateBlue, Brushes.DarkViolet, Brushes.MediumVioletRed, Brushes.IndianRed, Brushes.Firebrick, Brushes.Chocolate, Brushes.Peru, Brushes.Goldenrod };
        private string[] _BrushName = { "OliveDrab", "ForestGreen", "DarkCyan", "LightSlateGray", "RoyalBlue", "SlateBlue", "DarkViolet", "MediumVioletRed", "IndianRed", "Firebrick", "Chocolate", "Peru", "Goldenrod" };
        protected void Page_Load(object sender, EventArgs e)
        {
            string strCheckCode = CreateRandomCode(_CodeLength);
            Session["CheckCode"] = strCheckCode;
            SetNoCache();
            CreateImage(strCheckCode);
        }
        /// <summary>
        /// 获取验证码
        /// </summary>
        /// <param name="codeLength"></param>
        /// <returns></returns>
        private string CreateRandomCode(int codeLength)
        {
            string strChar = "0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,W,X,Y,Z";
            string[] arrayChars = strChar.Split(',');
            string strRandomCode = "";
            int temp = -1;

            for (int i = 0; i < codeLength; i++)
            {
                if (temp != -1)
                {
                    _Rand = new Random(i * temp * ((int)DateTime.Now.Ticks));
                }
                int t = _Rand.Next(arrayChars.Length);
                if (temp == t)
                {
                    return CreateRandomCode(codeLength);
                }
                temp = t;
                strRandomCode += arrayChars[t];
            }
            return strRandomCode;
        }
        /// <summary>
        /// 生成图片
        /// </summary>
        /// <param name="strCheckCode"></param>
        private void CreateImage(string strCheckCode)
        {           
            Bitmap objBitmap = null;
            Graphics g = null;            
            try
            {
                int iWidth = (int)(strCheckCode.Length * 15);//图片宽度n*15 高度：21
                objBitmap = new Bitmap(iWidth, 21);
                g = Graphics.FromImage(objBitmap);
                //绘画背景颜色
                g.Clear(Color.White);
                //绘画文字 
                g.DrawString(strCheckCode, GetFont(), GetBrush(), 3, 1);
                //绘画文字噪音点
                for (int n = 0; n < 30; n++)
                {
                    objBitmap.SetPixel(_Rand.Next(iWidth), _Rand.Next(21), Color.FromName(_BrushName[_BrushIndex]));
                }
                //绘画边框
                g.DrawRectangle(Pens.DarkGray, 0, 0, iWidth - 1, 20);
                objBitmap.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Gif);
                Response.ContentType = "image/gif";
            }
            catch { }
            finally
            {
                if (null != objBitmap)
                    objBitmap.Dispose();
                if (null != g)
                    g.Dispose();
            }
        }        
        //// <summary> 
        /// 设置页面不被缓存 
        /// </summary> 
        private void SetNoCache()
        {
            Response.Buffer = true;
            Response.ExpiresAbsolute = System.DateTime.Now.AddSeconds(-1);
            Response.Expires = 0;
            Response.CacheControl = "no-cache";
            Response.AppendHeader("Pragma", "No-Cache");
        }
        //// <summary> 
        /// 随机取一个字体 
        /// </summary> 
        /// <returns></returns> 
        private Font GetFont()
        {
            int fontIndex = _Rand.Next(0, _Fonts.Length);
            FontStyle fontStyle = GetFontStyle(_Rand.Next(0, 2));
            return new Font(_Fonts[fontIndex], 12, fontStyle);
        }
        //// <summary> 
        /// 取一个字体的样式 
        /// </summary> 
        /// <param name="index"></param> 
        /// <returns></returns> 
        private FontStyle GetFontStyle(int index)
        {
            switch (index)
            {
                case 0:
                    return FontStyle.Bold;
                case 1:
                    return FontStyle.Italic;
                default:
                    return FontStyle.Regular;
            }
        }
        //// <summary> 
        /// 随机取一个笔刷 
        /// </summary> 
        /// <returns></returns> 
        private Brush GetBrush()
        {
            _BrushIndex = _Rand.Next(0, _Brushs.Length);
            return _Brushs[_BrushIndex];
        }
    }
}